import sys
import os
import cv2
import vlc
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QPushButton, QFileDialog, QListWidget, QListWidgetItem, QLabel,
                             QSplitter, QTreeView, QFrame, QSlider, QMessageBox)
from PyQt5.QtCore import Qt, QDir, QTimer, QUrl, QSize, QModelIndex
from PyQt5.QtGui import QPixmap, QImage, QStandardItemModel, QStandardItem, QIcon, QPalette, QBrush
from history import VideoHistory

# 检测CUDA支持
use_cuda = False
try:
    if cv2.cuda.getCudaEnabledDeviceCount() > 0:
        use_cuda = True
        print("CUDA加速可用")
except:
    print("CUDA加速不可用")

class VideoPlayer(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Mars播放器")
        self.resize(1200, 700)
        
        # 设置无边框窗口，但保留系统按钮功能
        self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint | Qt.WindowSystemMenuHint | Qt.WindowMinMaxButtonsHint)
        
        # 设置窗口样式
        self.setStyleSheet(f"""
            QMainWindow {{
                background-color: #2A2A2A;
                border: 1px solid #8B1C1C;
                border-radius: 5px;
            }}
        """)
        
        # 创建缩略图缓存字典
        self.thumbnail_cache = {}
        
        # 初始化缩略图处理队列
        self.thumbnail_queue = []
        self.batch_size = 5
        self.is_processing = False
        
        # 定义一个更现代的火星红主题
        # 定义火星红主题色（调整为更鲜艳现代）
        self.mars_red = "#E63946"  # 主色调（更鲜艳现代）
        self.mars_red_dark = "#8B1C1C"  # 深色
        self.mars_red_light = "#FF6B6B"  # 亮色
        self.mars_red_hover = "#D84545"  # 悬停色
        self.text_color = "#F1FAEE"  # 文本颜色
        self.bg_dark = "#2A2A2A"  # 深色背景
        self.bg_medium = "#3A3A3A"  # 中等背景
        self.bg_light = "#4A4A4A"  # 浅色背景
        self.accent_color = "#FF9999"  # 强调色
        
        # 创建主窗口部件
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        
        # 创建自定义标题栏
        self.title_bar = QWidget()
        self.title_bar.setFixedHeight(40)
        title_layout = QHBoxLayout(self.title_bar)
        title_layout.setContentsMargins(10, 0, 10, 0)
        
        # 添加标题标签
        title_label = QLabel("Mars播放器")
        title_label.setStyleSheet(f"""
            color: {self.text_color};
            font-size: 14px;
            font-weight: bold;
        """)
        
        # 添加最小化、最大化和关闭按钮
        min_button = QPushButton("—")
        max_button = QPushButton("□")
        close_button = QPushButton("×")
        
        # 设置按钮样式
        button_style = f"""
            QPushButton {{
                background: transparent;
                border: none;
                color: {self.text_color};
                font-size: 16px;
                padding: 5px 10px;
            }}
            QPushButton:hover {{
                background-color: {self.mars_red_hover};
            }}
        """
        min_button.setStyleSheet(button_style)
        max_button.setStyleSheet(button_style)
        close_button.setStyleSheet(button_style + """
            QPushButton:hover {
                background-color: #FF4444;
            }
        """)
        
        # 设置按钮大小
        for btn in (min_button, max_button, close_button):
            btn.setFixedSize(40, 40)
        
        # 添加到标题栏布局
        title_layout.addWidget(title_label)
        title_layout.addStretch()
        title_layout.addWidget(min_button)
        title_layout.addWidget(max_button)
        title_layout.addWidget(close_button)
        
        # 设置标题栏样式
        self.title_bar.setStyleSheet(f"""
            QWidget {{
                background-color: {self.mars_red_dark};
                border-top-left-radius: 5px;
                border-top-right-radius: 5px;
            }}
        """)
        
        # 创建主布局
        main_layout = QVBoxLayout(self.central_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        
        # 添加标题栏和原有布局
        main_layout.addWidget(self.title_bar)
        
        # 创建一个容器来包含原有的布局
        content_widget = QWidget()
        main_layout.addWidget(content_widget)
        
        # 将原有的水平布局移动到content_widget
        self.main_layout = QHBoxLayout(content_widget)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        
        # 连接按钮信号
        min_button.clicked.connect(self.showMinimized)
        max_button.clicked.connect(self.toggle_maximize)
        close_button.clicked.connect(self.close)
        
        # 添加窗口拖动支持
        self.title_bar.mousePressEvent = self.title_bar_mouse_press
        self.title_bar.mouseMoveEvent = self.title_bar_mouse_move
        self.title_bar.mouseDoubleClickEvent = self.title_bar_double_click
        
        # 存储窗口状态
        self.is_maximized = False
        self.drag_position = None
        
        # 设置背景图片 - 使用更直接的方式
        bg_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bg.jpg")
        if os.path.exists(bg_path):
            # 使用QPalette设置背景
            palette = self.palette()
            pixmap = QPixmap(bg_path).scaled(self.size(), Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)
            palette.setBrush(QPalette.Window, QBrush(pixmap))
            self.setPalette(palette)
            self.setAutoFillBackground(True)
            
            # 同时设置中央部件样式
            self.central_widget.setStyleSheet("background: transparent;")
        
        # 设置窗口标题栏样式 - 更现代的火星红风格
        self.setStyleSheet("""
            QMainWindow::title {
                background-color: #8B1C1C;
                color: #F1FAEE;
            }
            QWidget {
                background-color: rgba(42, 42, 42, 0.7);
                color: #F1FAEE;
            }
            QPushButton { 
                background-color: #8B1C1C;
                color: #F1FAEE;
                border: none;
                padding: 10px 20px;
                border-radius: 5px;
                min-width: 90px;
                font-weight: bold;
            }
            QPushButton:hover { 
                background-color: #C83232;
                border-bottom: 2px solid #FF6B6B;
            }
            QPushButton:pressed {
                background-color: #6B1515;
            }
            QLabel { 
                color: #F1FAEE;
                font-size: 12px;
                font-weight: bold;
            }
            QSlider::groove:horizontal {
                background: #3A3A3A;
                height: 8px;
                border-radius: 4px;
            }
            QSlider::handle:horizontal {
                background: #E63946;
                width: 16px;
                height: 16px; 
                margin: -4px 0;
                border-radius: 8px;
            }
            QSlider::handle:horizontal:hover {
                background: #FF6B6B;
            }
            QSlider::sub-page:horizontal {
                background: #C83232;
                border-radius: 4px;
            }
            QTreeView, QListWidget {
                background-color: rgba(42, 42, 42, 0.7);
                border: none;
                border-radius: 5px;
                padding: 5px;
            }
            QTreeView::item, QListWidget::item {
                padding: 8px;
                border-radius: 4px;
                margin: 2px;
            }
            QTreeView::item:selected, QListWidget::item:selected {
                background-color: #C83232;
                color: #F1FAEE;
            }
            QTreeView::item:hover, QListWidget::item:hover {
                background-color: rgba(74, 74, 74, 0.5);
            }
        """)
        self.central_widget.setStyleSheet("")
        
        # 初始化历史记录管理器
        self.video_history = VideoHistory()
        
        # 创建分割器
        self.splitter = QSplitter(Qt.Horizontal)
        self.main_layout.addWidget(self.splitter)
        
        # 创建左侧视频播放区域
        self.video_container = QWidget()
        self.video_layout = QVBoxLayout(self.video_container)
        
        # 设置视频容器的背景为透明
        self.video_container.setStyleSheet("""
            background-color: transparent;
        """)
        
        # 创建VLC实例和视频播放器
        self.vlc_instance = vlc.Instance('--no-video-title-show --video-on-top --no-video-deco')
        self.media_player = self.vlc_instance.media_player_new()
        
        # 设置VLC播放器选项，使视频填充整个窗口
        self.media_player.video_set_scale(0)  # 0表示自动缩放
        self.media_player.video_set_aspect_ratio(None)  # 不保持宽高比，完全填充
        
        # 创建视频显示窗口
        self.video_widget = QFrame()
        self.video_widget.setMinimumSize(640, 480)
        self.video_widget.setStyleSheet("""
            QFrame {
                background-color: #1A1A1A;
                border: none;
                border-radius: 8px;
                margin: 5px;
            }
        """)
        
        # 创建视频布局，确保视频窗口填充整个区域
        video_layout = QVBoxLayout(self.video_widget)
        video_layout.setContentsMargins(0, 0, 0, 0)  # 移除所有边距
        video_layout.setSpacing(0)  # 移除间距
        
        # 将视频输出设置到QFrame窗口
        if sys.platform.startswith('linux'):  # Linux
            self.media_player.set_xwindow(self.video_widget.winId())
        elif sys.platform == "win32":  # Windows
            self.media_player.set_hwnd(self.video_widget.winId())
        
        # 创建控制按钮
        self.controls_widget = QWidget()
        # 设置控制栏的固定高度
        self.controls_widget.setFixedHeight(70)
        self.controls_layout = QHBoxLayout(self.controls_widget)
        self.controls_layout.setContentsMargins(15, 10, 15, 10)
        self.controls_layout.setSpacing(15)
        
        # 创建播放和停止按钮并设置样式
        button_style = """
            QPushButton {
                background-color: #8B1C1C;
                color: #F1FAEE;
                border: none;
                padding: 10px 20px;
                border-radius: 5px;
                min-width: 90px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #C83232;
                border-bottom: 2px solid #FF6B6B;
            }
            QPushButton:pressed {
                background-color: #6B1515;
            }
        """
        
        # 创建播放/暂停按钮
        self.play_button = QPushButton("播放")
        self.play_button.setStyleSheet(button_style)
        self.play_button.setFixedWidth(110)
        self.play_button.setFixedHeight(36)
        self.play_button.clicked.connect(self.toggle_play)
        
        # 创建进度条和时间标签
        self.position_slider = QSlider(Qt.Horizontal)
        self.position_slider.setRange(0, 0)
        # 连接进度条的值变化信号到设置位置的方法
        self.position_slider.sliderMoved.connect(self.set_position)
        # 增加进度条的最小高度，确保可见
        self.position_slider.setMinimumHeight(20)
        self.position_slider.setStyleSheet("""
            QSlider::groove:horizontal {
                background: #3A3A3A;
                height: 8px;
                border-radius: 4px;
            }
            QSlider::handle:horizontal {
                background: #E63946;
                width: 18px;
                height: 18px;
                margin: -5px 0;
                border-radius: 9px;
            }
            QSlider::handle:horizontal:hover {
                background: #FF6B6B;
                width: 20px;
                height: 20px;
                margin: -6px 0;
                border-radius: 10px;
            }
            QSlider::sub-page:horizontal {
                background: #C83232;
                border-radius: 4px;
            }
        """)
        
        self.time_label = QLabel("00:00 / 00:00")
        self.time_label.setStyleSheet("color: #F1FAEE; font-size: 13px; font-weight: bold;")
        self.time_label.setMinimumWidth(120)
        self.time_label.setAlignment(Qt.AlignCenter)
        
        # 添加音量控制
        volume_label = QLabel("音量:")
        volume_label.setStyleSheet("color: #F1FAEE; font-size: 13px; font-weight: bold;")
        
        self.volume_slider = QSlider(Qt.Horizontal)
        self.volume_slider.setRange(0, 100)
        self.volume_slider.setValue(50)
        self.volume_slider.setFixedWidth(100)
        self.volume_slider.valueChanged.connect(self.set_volume)
        self.volume_slider.setStyleSheet("""
            QSlider::groove:horizontal {
                background: #3A3A3A;
                height: 6px;
                border-radius: 3px;
            }
            QSlider::handle:horizontal {
                background: #E63946;
                width: 14px;
                height: 14px;
                margin: -4px 0;
                border-radius: 7px;
            }
            QSlider::handle:horizontal:hover {
                background: #FF6B6B;
                width: 16px;
                height: 16px;
                margin: -5px 0;
                border-radius: 8px;
            }
            QSlider::sub-page:horizontal {
                background: #C83232;
                border-radius: 3px;
            }
        """)
        
        # 添加全屏按钮
        self.fullscreen_button = QPushButton("全屏")
        self.fullscreen_button.clicked.connect(self.toggle_fullscreen)
        self.fullscreen_button.setStyleSheet(button_style)
        self.fullscreen_button.setFixedWidth(110)
        self.fullscreen_button.setFixedHeight(36)
        
        # 创建退出全屏按钮（初始隐藏）
        self.exit_fullscreen_button = QPushButton("退出全屏")
        self.exit_fullscreen_button.setStyleSheet("""
            QPushButton {
                background-color: #C83232;
                color: white;
                border: 2px solid white;
                border-radius: 15px;
                padding: 8px 15px;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #FF6B6B;
                border-color: #FFFFFF;
            }
        """)
        self.exit_fullscreen_button.setFixedSize(120, 40)
        self.exit_fullscreen_button.clicked.connect(self.toggle_fullscreen)
        self.exit_fullscreen_button.hide()  # 初始隐藏
        
        # 设置控件的初始可见性和样式
        self.controls_widget.setStyleSheet("""
            background-color: rgba(42, 42, 42, 0.85);
            border-radius: 10px;
            border: 1px solid #8B1C1C;
            padding: 5px;
        """)
        
        # 创建一个单独的小部件来包含进度条和时间标签
        progress_widget = QWidget()
        progress_layout = QHBoxLayout(progress_widget)
        progress_layout.setContentsMargins(0, 0, 0, 0)
        progress_layout.setSpacing(10)
        progress_layout.addWidget(self.position_slider, 1)
        progress_layout.addWidget(self.time_label)
        
        # 将控件添加到控制布局
        self.controls_layout.addWidget(self.play_button)
        self.controls_layout.addWidget(progress_widget, 1)  # 进度条区域占据更多空间
        self.controls_layout.addWidget(volume_label)
        self.controls_layout.addWidget(self.volume_slider)
        self.controls_layout.addWidget(self.fullscreen_button)
        self.controls_layout.addWidget(self.exit_fullscreen_button)
        
        # 添加视频播放器和控制按钮到左侧布局
        self.video_layout.addWidget(self.video_widget, 1)  # 视频区域占据所有可用空间
        
        # 创建一个水平布局来包含控制栏，使其居中显示
        self.controls_container = QWidget()
        self.controls_container.setFixedHeight(90)  # 设置容器的固定高度
        controls_container_layout = QHBoxLayout(self.controls_container)
        controls_container_layout.setContentsMargins(20, 10, 20, 10)
        
        # 将控制栏添加到居中布局
        controls_container_layout.addWidget(self.controls_widget)
        
        # 将包含控制栏的容器添加到视频布局，并设置为固定高度
        self.video_layout.addWidget(self.controls_container, 0)  # 控制栏不随窗口拉伸
        
        # 创建右侧文件夹和视频列表区域
        self.playlist_container = QWidget()
        self.playlist_layout = QVBoxLayout(self.playlist_container)
        
        # 设置播放列表容器的背景为半透明
        self.playlist_container.setStyleSheet("""
            background-color: rgba(42, 42, 42, 0.7);
            border-radius: 10px;
            border: 1px solid #8B1C1C;
            padding: 5px;
        """)
        
        # 创建选择文件夹按钮
        self.folder_button = QPushButton("选择文件夹")
        self.folder_button.setStyleSheet(button_style)
        self.folder_button.setFixedHeight(36)
        self.playlist_layout.addWidget(self.folder_button)
        
        # 创建文件夹树状视图
        self.folder_tree = QTreeView()
        self.folder_model = QStandardItemModel()
        self.folder_model.setHorizontalHeaderLabels(["文件夹"])
        self.folder_tree.setModel(self.folder_model)
        self.folder_tree.setStyleSheet("""
            QTreeView {
                background-color: rgba(42, 42, 42, 0.6);
                border: none;
                border-radius: 5px;
                padding: 5px;
            }
            QTreeView::item {
                padding: 8px;
                border-radius: 4px;
            }
            QTreeView::item:selected {
                background-color: #C83232;
                color: #F1FAEE;
            }
            QTreeView::item:hover {
                background-color: rgba(74, 74, 74, 0.5);
            }
            QTreeView::branch {
                background-color: transparent;
            }
        """)
        self.folder_tree.setMaximumHeight(140)  # 设置文件夹树的最大高度
        self.playlist_layout.addWidget(self.folder_tree)
        
        # 创建视频列表
        self.video_list_label = QLabel("视频列表:")
        self.video_list = QListWidget()
        self.video_list.setIconSize(QSize(120, 80))
        self.video_list.setResizeMode(QListWidget.Adjust)
        self.video_list.setViewMode(QListWidget.IconMode)
        self.video_list.setStyleSheet("""
            QListWidget {
                background-color: rgba(42, 42, 42, 0.6);
                border: none;
                border-radius: 5px;
                padding: 10px;
            }
            QListWidget::item {
                background-color: rgba(58, 58, 58, 0.5);
                border-radius: 8px;
                margin: 5px;
                padding: 5px;
            }
            QListWidget::item:selected {
                background-color: #C83232;
                color: #F1FAEE;
                border: none;
            }
            QListWidget::item:hover {
                background-color: rgba(74, 74, 74, 0.7);
                border: 1px solid #FF6B6B;
            }
        """)
        self.video_list.setSpacing(10)  # 添加项目间距
        self.video_list.setWrapping(True)  # 确保自动换行
        self.playlist_layout.addWidget(self.video_list_label)
        self.playlist_layout.addWidget(self.video_list)
        
        # 设置布局比例
        self.playlist_layout.setStretchFactor(self.folder_tree, 2)  # 文件夹树占2
        self.playlist_layout.setStretchFactor(self.video_list, 8)  # 视频列表占8
        
        # 添加左右两侧到分割器
        self.splitter.addWidget(self.video_container)
        self.splitter.addWidget(self.playlist_container)
        self.splitter.setSizes([800, 400])  # 调整分割比例，使右侧区域更紧凑
        self.splitter.setStretchFactor(0, 2)  # 设置左侧视频区域的拉伸因子
        self.splitter.setStretchFactor(1, 1)  # 设置右侧列表区域的拉伸因子
        
        # 连接信号和槽
        self.folder_button.clicked.connect(self.select_folder)
        self.folder_tree.clicked.connect(self.folder_clicked)
        self.video_list.itemDoubleClicked.connect(self.video_double_clicked)
        self.play_button.clicked.connect(self.toggle_play)
        
        # 创建定时器用于更新进度条
        self.update_timer = QTimer(self)
        self.update_timer.setInterval(100)  # 每100ms更新一次
        self.update_timer.timeout.connect(self.update_position)
        
        # 创建定时器用于自动隐藏控制栏
        self.hide_controls_timer = QTimer(self)
        self.hide_controls_timer.setInterval(3000)  # 3秒后自动隐藏
        self.hide_controls_timer.setSingleShot(True)  # 只触发一次
        self.hide_controls_timer.timeout.connect(self.hide_controls)
        
        # 存储当前视频文件夹路径
        self.current_folder = ""
        self.video_extensions = [".mp4", ".avi", ".mkv", ".mov", ".wmv"]
        
        # 添加全屏状态标志
        self.is_fullscreen = False
        
        # 保存原始窗口标志
        self.original_window_flags = self.windowFlags()
        
        # 添加调试标志
        self.debug_mode = True  # 设置为True启用调试输出
        
        # 添加控件可见性检查定时器
        self.visibility_check_timer = QTimer(self)
        self.visibility_check_timer.setInterval(1000)  # 每秒检查一次
        self.visibility_check_timer.timeout.connect(self.check_controls_visibility)
        
        # 初始化窗口状态
        self.was_maximized = False
        self.normal_geometry = None
    
    def select_folder(self):
        folder = QFileDialog.getExistingDirectory(self, "选择文件夹")
        if folder:
            self.current_folder = folder
            self.update_folder_tree(folder)
            self.load_videos_from_folder(folder)  # 自动加载视频列表
    
    def update_folder_tree(self, root_path):
        self.folder_model.clear()
        self.folder_model.setHorizontalHeaderLabels(["文件夹"])
        
        root_item = QStandardItem(QIcon("folder.png"), os.path.basename(root_path))
        root_item.setData(root_path)
        self.folder_model.appendRow(root_item)
        
        self.populate_folder_tree(root_item, root_path)
        self.folder_tree.expandAll()
    
    def populate_folder_tree(self, parent_item, parent_path):
        for item in os.listdir(parent_path):
            item_path = os.path.join(parent_path, item)
            if os.path.isdir(item_path):
                folder_item = QStandardItem(QIcon("folder.png"), item)
                folder_item.setData(item_path)
                parent_item.appendRow(folder_item)
                self.populate_folder_tree(folder_item, item_path)
    
    def folder_clicked(self, index):
        item = self.folder_model.itemFromIndex(index)
        folder_path = item.data()
        if folder_path:
            self.load_videos_from_folder(folder_path)
    
    def load_videos_from_folder(self, folder_path):
        self.video_list.clear()
        self.thumbnail_queue.clear()
        
        # 收集所有视频文件
        for file in os.listdir(folder_path):
            file_path = os.path.join(folder_path, file)
            if os.path.isfile(file_path) and any(file.lower().endswith(ext) for ext in self.video_extensions):
                self.add_video_to_list(file_path)
        
        # 开始批量处理缩略图
        if not self.is_processing:
            self.process_thumbnail_batch()

    def add_video_to_list(self, video_path):
        # 创建列表项
        item = QListWidgetItem()
        item.setText(os.path.basename(video_path))
        item.setData(Qt.UserRole, video_path)
        item.setSizeHint(QSize(160, 130))  # 增加项目大小
        item.setTextAlignment(Qt.AlignCenter)  # 文本居中
        
        # 先添加到列表，使用默认图标
        item.setIcon(QIcon("video.png"))
        self.video_list.addItem(item)
        
        # 检查缓存中是否已有缩略图
        if video_path in self.thumbnail_cache:
            item.setIcon(QIcon(self.thumbnail_cache[video_path]))
        else:
            # 添加到处理队列
            self.thumbnail_queue.append((item, video_path))

    def process_thumbnail_batch(self):
        if not self.thumbnail_queue:
            self.is_processing = False
            return
        
        self.is_processing = True
        batch = self.thumbnail_queue[:self.batch_size]
        
        for item, video_path in batch:
            if video_path in self.thumbnail_cache:
                item.setIcon(QIcon(self.thumbnail_cache[video_path]))
                continue
                
            # 使用OpenCV获取视频缩略图
            cap = cv2.VideoCapture(video_path)
            ret, frame = cap.read()
            
            if ret:
                # 使用CUDA加速图像处理（如果可用）
                if use_cuda:
                    gpu_frame = cv2.cuda_GpuMat()
                    gpu_frame.upload(frame)
                    gpu_frame = cv2.cuda.resize(gpu_frame, (80, 60))
                    frame = gpu_frame.download()
                else:
                    frame = cv2.resize(frame, (80, 60))
                
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                image = QImage(frame.data, frame.shape[1], frame.shape[0], frame.shape[1] * 3, QImage.Format_RGB888)
                pixmap = QPixmap.fromImage(image)
                self.thumbnail_cache[video_path] = pixmap
                item.setIcon(QIcon(pixmap))
            
            cap.release()
        
        # 移除已处理的项
        self.thumbnail_queue = self.thumbnail_queue[self.batch_size:]
        
        # 继续处理下一批
        if self.thumbnail_queue:
            QTimer.singleShot(10, self.process_thumbnail_batch)
        else:
            self.is_processing = False
    
    def load_thumbnail_async(self, item, video_path):
        # 如果已经在缓存中，直接使用缓存
        if video_path in self.thumbnail_cache:
            item.setIcon(QIcon(self.thumbnail_cache[video_path]))
            return
            
        # 使用OpenCV获取视频缩略图
        cap = cv2.VideoCapture(video_path)
        ret, frame = cap.read()
        
        if ret:
            # 减小缩略图尺寸
            frame = cv2.resize(frame, (80, 60))
            # 转换颜色从BGR到RGB
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            # 创建QImage
            image = QImage(frame.data, frame.shape[1], frame.shape[0], frame.shape[1] * 3, QImage.Format_RGB888)
            # 创建QPixmap
            pixmap = QPixmap.fromImage(image)
            # 保存到缓存
            self.thumbnail_cache[video_path] = pixmap
            item.setIcon(QIcon(pixmap))
        
        cap.release()
    
    def video_double_clicked(self, item):
        video_path = item.data(Qt.UserRole)
        self.play_video(video_path)
    
    def play_video(self, video_path):
        if not os.path.exists(video_path):
            QMessageBox.warning(self, "错误", f"视频文件不存在：{video_path}")
            return
        
        try:
            # 创建媒体并加载视频
            media = self.vlc_instance.media_new(video_path)
            
            # 添加媒体选项，强制填充
            media.add_option(":avcodec-hw=any")  # 启用硬件加速
            media.add_option(":video-filter=croppadd{cropleft=0,croptop=0,cropright=0,cropbottom=0}")  # 移除任何裁剪
            
            self.media_player.set_media(media)
            
            # 如果是全屏模式，设置视频填充整个屏幕
            if self.is_fullscreen:
                self.media_player.video_set_aspect_ratio("0:0")  # 强制拉伸填充
                self.media_player.video_set_scale(1.0)  # 设置缩放比例为1.0
                
                # 确保视频窗口完全填充屏幕
                screen_size = QApplication.desktop().screenGeometry()
                self.video_widget.setGeometry(0, 0, screen_size.width(), screen_size.height())
            
            # 播放视频
            self.play_button.setText("暂停")
            self.media_player.play()
            self.update_timer.start()  # 开始播放时启动更新进度条
            
            # 添加到播放历史
            self.video_history.add_video(video_path)
            
            if self.debug_mode:
                print(f"播放视频: {video_path}")
                print(f"全屏状态: {self.is_fullscreen}")
                print(f"视频宽高比设置: {self.media_player.video_get_aspect_ratio()}")
                print(f"视频缩放设置: {self.media_player.video_get_scale()}")
            
        except Exception as e:
            QMessageBox.warning(self, "播放错误", f"无法播放视频：{str(e)}")
            return
        
    def handle_media_error(self):
        error = self.media_player.error()
        if error != QMediaPlayer.NoError:
            QMessageBox.warning(self, "播放错误", f"视频播放出错：{self.media_player.errorString()}")
            
    def handle_state_changed(self, state):
        # 根据播放状态更新按钮文本
        if state == vlc.State.Playing:
            self.play_button.setText("暂停")
        else:
            self.play_button.setText("播放")
    
    def toggle_play(self):
        if self.media_player.is_playing():
            self.media_player.pause()
            self.play_button.setText("播放")
            self.update_timer.stop()
        else:
            if self.media_player.get_media():
                self.media_player.play()
                self.play_button.setText("暂停")
                self.update_timer.start()
            else:
                # 如果没有加载媒体，可以提示用户选择视频
                QMessageBox.information(self, "提示", "请先选择一个视频文件播放")
    
    def set_volume(self, volume):
        self.media_player.audio_set_volume(volume)

    def eventFilter(self, obj, event):
        if obj == self.video_widget:
            # 处理鼠标移动事件
            if event.type() == event.MouseMove:
                if self.is_fullscreen:
                    if self.debug_mode:
                        print("捕获到鼠标移动事件")
                    # 显示控制栏和退出全屏按钮
                    self.show_controls()
                    # 重置定时器
                    self.hide_controls_timer.start()
            # 处理鼠标点击事件 - 确保点击时也显示控件
            elif event.type() == event.MouseButtonPress:
                if self.is_fullscreen:
                    if self.debug_mode:
                        print("捕获到鼠标点击事件")
                    self.show_controls()
                    self.hide_controls_timer.start()
            # 处理鼠标离开事件
            elif event.type() == event.Leave:
                if self.is_fullscreen:
                    if self.debug_mode:
                        print("捕获到鼠标离开事件")
                    # 只在鼠标真正离开窗口时隐藏控件
                    cursor_pos = QApplication.desktop().cursor().pos()
                    if not self.geometry().contains(cursor_pos):
                        if self.debug_mode:
                            print("鼠标离开窗口，隐藏控制栏")
                        self.controls_widget.hide()
            # 处理窗口大小变化事件
            elif event.type() == event.Resize:
                if self.is_fullscreen:
                    if self.debug_mode:
                        print("捕获到窗口大小变化事件")
                    # 窗口大小变化时重新显示控件
                    self.show_controls()
        return super().eventFilter(obj, event)
    
    def show_controls(self):
        if self.is_fullscreen:
            if self.debug_mode:
                print("显示控件")
            
            # 计算控件位置
            screen_rect = self.geometry()  # 使用主窗口的几何信息
            controls_height = self.controls_widget.sizeHint().height()
            
            # 将控制栏放在底部中央
            self.controls_widget.setGeometry(
                (screen_rect.width() - 700) // 2,  # 居中
                screen_rect.height() - controls_height - 20,  # 底部上方20像素
                700,  # 固定宽度
                controls_height
            )
            
            # 设置退出全屏按钮位置（右上角）
            self.exit_fullscreen_button.setGeometry(
                screen_rect.width() - 150,  # 右边距离30像素
                30,  # 顶部距离30像素
                120,  # 宽度
                40   # 高度
            )
            
            # 确保控件可见
            self.controls_widget.show()
            self.controls_widget.raise_()
            self.exit_fullscreen_button.show()
            self.exit_fullscreen_button.raise_()
            
            # 强制更新
            QApplication.processEvents()
            
            if self.debug_mode:
                print(f"控件位置: 控制栏={self.controls_widget.geometry()}, 退出按钮={self.exit_fullscreen_button.geometry()}")
                print(f"控件可见性: 控制栏可见={self.controls_widget.isVisible()}, 退出按钮可见={self.exit_fullscreen_button.isVisible()}")
            
            # 重置隐藏控制栏的定时器
            self.hide_controls_timer.start()
    
    def hide_controls(self):
        self.controls_widget.hide()
        self.mouse_idle = True
    
    def toggle_fullscreen(self):
        """使用Qt自身的全屏管理而不是VLC的"""
        print(f"调用toggle_fullscreen - 当前全屏状态: {self.is_fullscreen}")
        if not self.is_fullscreen:
            # 保存当前状态
            self.normal_geometry = self.geometry()
            self.was_maximized = self.isMaximized()
            print(f"保存窗口状态 - 是否最大化: {self.was_maximized}, 几何信息: {self.normal_geometry}")
            
            # 隐藏不需要的控件
            self.playlist_container.hide()
            self.fullscreen_button.setText("退出全屏")
            
            # 进入全屏
            print("正在进入全屏模式...")
            self.showFullScreen()
            self.is_fullscreen = True
            
            # 设置视频容器为固定黑色背景，增强全屏体验
            if hasattr(self, 'video_container') and self.video_container:
                self.video_container.setStyleSheet("background-color: black;")
                
                # 移除边距和边框
                if hasattr(self, 'main_layout'):
                    self.main_layout.setContentsMargins(0, 0, 0, 0)
                self.video_container.setContentsMargins(0, 0, 0, 0)
                
                # 确保视频填满整个可用空间
                if hasattr(self, 'video_widget') and self.video_widget:
                    self.video_widget.setGeometry(self.video_container.rect())
            
            # 确保视频控件填充整个窗口
            print("安排延迟更新视频几何信息...")
            # 立即更新一次
            self.update_video_geometry()
            # 然后延迟100ms再次更新，以适应窗口变化
            QTimer.singleShot(100, self.update_video_geometry)
            # 延迟500ms再次更新，以确保视频显示正确
            QTimer.singleShot(500, self.update_video_geometry)
        else:
            # 退出全屏
            print("正在退出全屏模式...")
            self.fullscreen_button.setText("全屏")
            self.playlist_container.show()
            
            # 恢复原来的窗口状态
            if self.was_maximized:
                print("恢复到最大化状态")
                self.showMaximized()
            else:
                print(f"恢复到普通状态，几何信息: {self.normal_geometry}")
                self.showNormal()
                if self.normal_geometry:
                    self.setGeometry(self.normal_geometry)
            
            # 恢复样式和边距
            if hasattr(self, 'video_container') and self.video_container:
                self.video_container.setStyleSheet("")
                self.video_container.setContentsMargins(1, 1, 1, 1)
                
            if hasattr(self, 'main_layout'):
                self.main_layout.setContentsMargins(10, 10, 10, 10)
                    
            self.is_fullscreen = False
            self.splitter.setSizes([800, 400])
            
            # 确保视频控件大小正确
            print("安排延迟更新视频几何信息...")
            # 立即更新一次
            self.update_video_geometry()
            # 然后延迟更新
            QTimer.singleShot(100, self.update_video_geometry)
            QTimer.singleShot(500, self.update_video_geometry)
    
    def update_video_geometry(self):
        """更新视频窗口的大小和位置"""
        print("执行update_video_geometry...")
        
        # 确保视频控件填充整个视频容器区域
        if hasattr(self, 'video_container') and self.video_container:
            container_rect = self.video_container.contentsRect()
            print(f"视频容器尺寸: {container_rect.width()}x{container_rect.height()}")
            
            # 设置视频窗口大小
            self.video_widget.setGeometry(container_rect)
            print(f"视频窗口尺寸设置为: {self.video_widget.width()}x{self.video_widget.height()}")
            
        # 强制更新播放器布局
        if hasattr(self, 'media_player') and self.media_player:
            # 刷新VLC的视频输出大小
            if self.media_player.get_media():
                current_state = self.media_player.get_state()
                current_time = self.media_player.get_time()
                
                # 只有在播放状态才需要优化
                if current_state == vlc.State.Playing:
                    print("正在播放中，强制更新视频显示...")
                    # 强制VLC重新计算视频输出尺寸
                    self.video_widget.updateGeometry()
                    self.video_widget.update()
                else:
                    print(f"视频未播放，当前状态: {current_state}")
    
    def keyPressEvent(self, event):
        # 添加键盘快捷键支持
        if event.key() == Qt.Key_F:
            if self.debug_mode:
                print("按下F键，切换全屏")
            self.toggle_fullscreen()
        elif event.key() == Qt.Key_Escape and self.is_fullscreen:
            if self.debug_mode:
                print("按下ESC键，退出全屏")
            self.toggle_fullscreen()
        elif event.key() == Qt.Key_Space:
            if self.debug_mode:
                print("按下空格键，切换播放/暂停")
            self.toggle_play()
        elif event.key() == Qt.Key_C and self.is_fullscreen:
            if self.debug_mode:
                print("按下C键，显示控件")
            self.show_controls()
        event.accept()
    
    def update_position(self):
        if not self.media_player.is_playing():
            return
            
        # 获取当前播放时长（毫秒）
        length = self.media_player.get_length()
        if length > 0:
            # 设置进度条范围
            self.position_slider.setRange(0, length)
            
            # 获取当前播放位置
            time = self.media_player.get_time()
            
            # 只有当用户没有拖动滑块时才更新位置
            if not self.position_slider.isSliderDown():
                # 只有当值发生变化时才更新，避免滑块闪烁
                if self.position_slider.value() != time:
                    self.position_slider.setValue(time)
            
            # 更新时间显示
            current = self.format_time(time)
            total = self.format_time(length)
            self.time_label.setText(f"{current} / {total}")
    
    def format_time(self, ms):
        # 将毫秒转换为时:分:秒格式
        seconds = ms // 1000
        hours = seconds // 3600
        minutes = (seconds % 3600) // 60
        seconds = seconds % 60
        return f"{hours:02d}:{minutes:02d}:{seconds:02d}"

    def set_position(self, position):
        # 设置播放位置（毫秒）
        if self.media_player.is_playing():
            self.media_player.set_time(position)
            
            # 立即更新时间显示，不等待下一次计时器触发
            time = position
            length = self.media_player.get_length()
            if length > 0:
                current = self.format_time(time)
                total = self.format_time(length)
                self.time_label.setText(f"{current} / {total}")

    def check_controls_visibility(self):
        if self.is_fullscreen:
            if self.debug_mode:
                print(f"控件可见性检查: 控制栏可见={self.controls_widget.isVisible()}, 退出按钮可见={self.exit_fullscreen_button.isVisible()}")
            
            # 如果控件不可见，尝试显示它们
            if not self.exit_fullscreen_button.isVisible():
                if self.debug_mode:
                    print("退出全屏按钮不可见，强制显示")
                self.exit_fullscreen_button.show()
                self.exit_fullscreen_button.raise_()

    def title_bar_mouse_press(self, event):
        if event.button() == Qt.LeftButton:
            self.drag_position = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def title_bar_mouse_move(self, event):
        if event.buttons() == Qt.LeftButton:
            self.move(event.globalPos() - self.drag_position)
            event.accept()

    def title_bar_double_click(self, event):
        if event.button() == Qt.LeftButton:
            self.toggle_maximize()
            event.accept()

    def toggle_maximize(self):
        if self.isMaximized():
            self.showNormal()
        else:
            self.showMaximized()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    player = VideoPlayer()
    player.show()
    sys.exit(app.exec_())